/**
 * 第三方平台自己相关服务
 * @authors 杨兴洲（of2502）
 * @date    2017/2/22 15:58
 * @version 1.0
 */
/// <reference path="./site-service.d.ts" />
import CONFIG from '../config';
import Site from '../model/site';
import WeixinService from '../service/weixin-service';
const appID = CONFIG.appID;

export default class SiteService {
  /**
     * 获取Site信息
     */
  static async getInfo(field?: string): Promise<any> {
    const doc = await Site.findOne({ appID }, { _id: 0 });
    return field ? doc[field] : doc;
  }

  /**
     * 保存Site信息
     */
  static async updateInfo(data): Promise<object> {
    return await Site.findOneAndUpdate({ appID }, data, { upsert: true });
  }

  static async getAccessTokenInfo():Promise<any>{
      const { accessToken, verifyTicket, expireAt } = await SiteService.getInfo();
      let result={accessToken,expiresTime:expireAt};
      if (new Date() > expireAt || !accessToken) {
          const { component_access_token, expires_in } = await WeixinService.getAccessToken(verifyTicket);
          let _expireAt = new Date(+new Date() + (expires_in - 200) * 1000);
          await SiteService.updateInfo({
              accessToken: component_access_token,
              expireAt:_expireAt
          });
          Object.assign(result,{
              accessToken: component_access_token,
              expiresTime: _expireAt
          });
      }
      return result;
  }

  /**
     * 获取AccessToken
     * @returns {Promise<string>}
     */
  static async getAccessToken(): Promise<string> {
    const { accessToken, verifyTicket, expireAt } = await SiteService.getInfo();
    if (new Date() > expireAt || !accessToken) {
      const { component_access_token, expires_in } = await WeixinService.getAccessToken(verifyTicket);
      await SiteService.updateInfo({
        accessToken: component_access_token,
        expireAt: new Date(+new Date() + (expires_in - 200) * 1000)
      });
      return component_access_token;
    }
    return accessToken;
  }
}
